package cn.e3mall.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.e3mall.common.jedis.JedisClient;
import cn.e3mall.common.pojo.EasyUIDataGridResult;
import cn.e3mall.common.util.E3Result;
import cn.e3mall.common.util.IDUtils;
import cn.e3mall.common.util.JsonUtils;
import cn.e3mall.mapper.TbItemDescMapper;
import cn.e3mall.mapper.TbItemMapper;
import cn.e3mall.pojo.TbItem;
import cn.e3mall.pojo.TbItemDesc;
import cn.e3mall.pojo.TbItemExample;
import cn.e3mall.pojo.TbItemExample.Criteria;
import cn.e3mall.service.ItemService;

/**
 * 商品管理Service
 * 
 * @author zhouzhixiang
 *
 */

@Service
public class ItemServiceImpl implements ItemService {

	@Autowired
	private TbItemMapper itemMapper;
	@Autowired
	private TbItemDescMapper ibItemDescMapper;
	@Autowired
	private JmsTemplate jmstemplate;
	@Resource(name = "topicDestination")
	private Destination topicDestination;
	@Autowired
	private JedisClient jedisClient;
	@Value("${REDIS_ITEM_PRE}")
	private String REDIS_ITEM_PRE;
	@Value("${TIEM_CACHE_EXPIRE}")
	private Integer TIEM_CACHE_EXPIRE;

	@Override
	public TbItem getItemById(long itemId) {
		// 查询缓存
		try {
			String jsonStr = jedisClient.get(REDIS_ITEM_PRE + ":" + itemId + ":BASE");
			if (StringUtils.isNotBlank(jsonStr)) {
				TbItem item = JsonUtils.jsonToPojo(jsonStr, TbItem.class);
				return item;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 缓存没有，查询数据库
		// 根据主键查询
		// TbItem tbItem= itemMapper.selectByPrimaryKey(itemid);
		TbItemExample example = new TbItemExample();
		Criteria criteria = example.createCriteria();
		// 设置查询条件
		criteria.andIdEqualTo(itemId);
		// 执行查询条件
		List<TbItem> list = itemMapper.selectByExample(example);
		if (list != null && list.size() > 0) {
			// 把结果添加到缓存
			try {
				jedisClient.set(REDIS_ITEM_PRE + ":" + itemId + ":BASE", JsonUtils.objectToJson(list.get(0)));
				// 设置过期时间
				jedisClient.expire(REDIS_ITEM_PRE + ":" + itemId + ":BASE", TIEM_CACHE_EXPIRE);
			} catch (Exception e) {
				e.printStackTrace();
			}

			return list.get(0);
		}
		return null;
	}

	@Override
	public EasyUIDataGridResult getItemList(int page, int rows) {
		// 设置分页信息
		PageHelper.startPage(page, rows);
		// 执行查询
		TbItemExample example = new TbItemExample();
		List<TbItem> list = itemMapper.selectByExample(example);
		// 取分页信息

		PageInfo<TbItem> pageInfo = new PageInfo<>(list);

		// 创建返回结果对象
		EasyUIDataGridResult result = new EasyUIDataGridResult();
		result.setTotal(pageInfo.getTotal());
		result.setRows(list);
		return result;
	}

	@Override
	public E3Result addItem(TbItem item, String desc) {
		// 生产商品id
		final long itemId = IDUtils.genItemId();
		// 补全item的属性
		item.setId(itemId);
		// 1 正常 2 下架 3 删除
		item.setStatus((byte) 1);
		item.setCreated(new Date());
		item.setUpdated(new Date());
		itemMapper.insert(item);
		// 向商品描述插入数据
		TbItemDesc tbItemDesc = new TbItemDesc();
		tbItemDesc.setItemId(itemId);
		tbItemDesc.setCreated(new Date());
		tbItemDesc.setUpdated(new Date());
		tbItemDesc.setItemDesc(desc);
		ibItemDescMapper.insert(tbItemDesc);
		// 发送商品添加消息到
		jmstemplate.send(topicDestination, new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				TextMessage textMessage = session.createTextMessage(itemId + "");
				return textMessage;
			}
		});

		// 返回成功！！
		return E3Result.ok();
	}

	/*
	 * 用于后台修改商品时的显示
	 * 
	 * @see cn.e3mall.service.ItemService#showItem(long)
	 */
	@Override
	public E3Result showItem(long TbItemId) {
		TbItem item = itemMapper.selectByPrimaryKey(TbItemId);
		E3Result result = new E3Result(item);
		return result;
	}

	/*
	 * 用于后台修改商品时的其内容介绍显示
	 * 
	 * @see cn.e3mall.service.ItemService#showItem(long)
	 */
	@Override
	public E3Result showItemDesc(long TbItemId) {
		TbItemDesc itemDesc = ibItemDescMapper.selectByPrimaryKey(TbItemId);
		E3Result result = new E3Result(itemDesc);
		return result;
	}

	// 修改商品
	@Override
	public E3Result editItem(TbItem item, String desc) {
		// 补全item的属性
		item.setUpdated(new Date());
		int upcount = itemMapper.updateByPrimaryKeySelective(item);
		// 补全itemDesc的属性
		TbItemDesc tItemDesc = new TbItemDesc();
		tItemDesc.setItemId(item.getId());
		tItemDesc.setUpdated(new Date());
		tItemDesc.setItemDesc(desc);
		int updescCount = ibItemDescMapper.updateByPrimaryKeySelective(tItemDesc);
		return E3Result.ok();
	}

	// 删除商品
	@Override
	public E3Result delItem(long TbItemId) {
		int count = itemMapper.deleteByPrimaryKey(TbItemId);
		return E3Result.ok();
	}

	// 根据商品取商品描述
	@Override
	public TbItemDesc getItemDescById(long itemId) {
		// 查询缓存
		try {
			String jsonStr = jedisClient.get(REDIS_ITEM_PRE + ":" + itemId + ":DESC");
			if (StringUtils.isNotBlank(jsonStr)) {
				TbItemDesc tbItemDesc = JsonUtils.jsonToPojo(jsonStr, TbItemDesc.class);
				return tbItemDesc;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		//查询商品描述
		TbItemDesc tbItemDesc = ibItemDescMapper.selectByPrimaryKey(itemId);
		
		try {
			jedisClient.set(REDIS_ITEM_PRE + ":" + itemId + ":DESC", JsonUtils.objectToJson(tbItemDesc));
			// 设置过期时间
			jedisClient.expire(REDIS_ITEM_PRE + ":" + itemId + ":DESC", TIEM_CACHE_EXPIRE);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return tbItemDesc;
	}

}
